package net.diaowen.dwsurvey.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.diaowen.common.utils.SystemUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.diaowen.common.base.dao.UserGroupDao;
import net.diaowen.common.base.entity.User;
import net.diaowen.common.base.entity.UserGroup;
import net.diaowen.common.base.service.AccountManager;
import net.diaowen.common.service.BaseServiceImpl;
import net.diaowen.common.utils.excel.ReadExcelUtil;
import net.diaowen.dwsurvey.service.GroupManager;
import net.diaowen.dwsurvey.service.UserGroupManager;
import net.diaowen.dwsurvey.service.UserManager;

import static net.diaowen.common.utils.SystemUtils.getCellValue;


/**
 * 分组管理
 * @author zhangyuting
 * @date 2019年5月8日
 *
 */
@Service
public class UserGroupManagerImpl extends BaseServiceImpl<UserGroup, String> implements UserGroupManager {
	
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private GroupManager groupManager;
	
	@Autowired
	private UserGroupDao userGroupDao;
	
	@Autowired
	private AccountManager accountManager;

	@Override
	public void setBaseDao() {
		this.baseDao=userGroupDao;
	}
	


	@Override
	public void adminSave(UserGroup entity) throws Exception {
		if(entity!=null){
			try {
				save(entity);
				getBaseDao().flush();
	
			} catch (Exception e) {
				 e.printStackTrace();
				throw new Exception(e);
				
			}
		}
		
	}



	@Override
	public List<UserGroup> findListByUserId(String userId) {
		Criterion criterion=Restrictions.eq("userId", userId);
		return findList(criterion);
	}
	
	@Override
	public List<UserGroup> findListByGroupId(String usergroupId) {
		Criterion criterion=Restrictions.eq("usergroupId", usergroupId);
		return findList(criterion);
	}
	
	@Override
	public UserGroup findListByGroupIdAndUserId(String usergroupId, String userId) {
		List<Criterion> criterions=new ArrayList<Criterion>();
		criterions.add(Restrictions.eq("usergroupId", usergroupId));
		criterions.add(Restrictions.eq("userId", userId));
		return userGroupDao.findFirst(criterions);
	}
	
	@Override
	public void delete(String usergroupId,String userId) {
		UserGroup ug = findListByGroupIdAndUserId(usergroupId,userId);
		userGroupDao.delete(ug.getId());
	}


	
	@SuppressWarnings("deprecation")
	@Override
	public Map<String,Object> doBatchImport(String filepath, String groupId) {
		HSSFWorkbook workBook;
		List<String> msg = new ArrayList<String>();
		Map<String,Object> map = new HashMap<String,Object>();
		int rowNum = 0;
		int successcnt = 0;
		int effectiveNum = 0;

		workBook = ReadExcelUtil.getWorkBook(filepath);
		HSSFSheet hssfSheet = ReadExcelUtil.getHSSFSheet(workBook,0);
		rowNum = hssfSheet.getPhysicalNumberOfRows();
		
		//查询当登录用户
		User curUser = null;
		try {
			//开始插入
			 curUser = accountManager.getCurUser();
		}catch (Exception e){
			e.getMessage();
			msg.add("查询当前用户失败"+ e.getMessage());
			map.put("msg", msg);
			map.put("rowNum", effectiveNum);
			map.put("successcnt", successcnt);
			return map;
		}

		//如果是超级系统管理员，则去小组表取orgId
		String orgId = "";
		if(curUser.getSystemRole() == 8) {
			orgId = groupManager.findOne(groupId).getOrgId();
		} else {
			orgId = curUser.getOrgId();
		}

		for(int j = 1; j < rowNum; j++) {
			try {
			HSSFRow row = hssfSheet.getRow(j);
			effectiveNum = effectiveNum + 1;
			//开始验证excle格式
			String ex_phone = SystemUtils.getCellValue(row.getCell(0));
			String ex_email = SystemUtils.getCellValue(row.getCell(1));
			String ex_name = SystemUtils.getCellValue(row.getCell(2));
			String ex_school = SystemUtils.getCellValue(row.getCell(3));
			String ex_college = SystemUtils.getCellValue(row.getCell(4));
			String ex_major =  SystemUtils.getCellValue(row.getCell(5));
			String ex_studengId =  SystemUtils.getCellValue(row.getCell(6));
			//第七列特殊，做日期格式化
			String ex_entime = SystemUtils.getCellValueDate(row.getCell(7));
			String ex_sex =  SystemUtils.getCellValue(row.getCell(8));
			String ex_province = SystemUtils.getCellValue(row.getCell(9));
			//TODO 每一列都循环验证
			
			
			User user = new User();
			user.setCellphone(ex_phone);
			user.setEmail(ex_email);
			user.setPwd(ex_email);
			user.setName(ex_name);
			user.setSchool(ex_school);
			user.setMajor(ex_major);
			user.setCollege(ex_college);
			user.setStudentId(ex_studengId);


			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date edate = dateFormat.parse(ex_entime);
			user.setEnrollmentTime(edate);
			user.setEnrollmentTimeStr(ex_entime);
			if(ex_sex.equals("男")){
				user.setSex(0);
			} else {
				user.setSex(1);
			}
			user.setProvince(ex_province);



			//判断是否有重复的用户
			User userTemp = userManager.findOrgStudentId(orgId,user.getStudentId());

			UserGroup userGroup = new UserGroup();
			if (userTemp != null) {
				userGroup.setUserId(userTemp.getId());
				userGroup.setUsergroupId(groupId);
				try {
					//已经存在这个用户的话，更新一波这个用户的信息
					userTemp.setCellphone(user.getCellphone());
					userTemp.setEmail(user.getEmail());
					//userTemp.setPwd(user.getPwd());
					userTemp.setName(user.getName());
					userTemp.setSchool(user.getSchool());
					userTemp.setMajor(user.getMajor());
					userTemp.setCollege(user.getCollege());
					userTemp.setStudentId(user.getStudentId());
					userTemp.setEnrollmentTime(user.getEnrollmentTime());
					userTemp.setEnrollmentTimeStr(user.getEnrollmentTimeStr());
					userTemp.setSex(user.getSex());
					userTemp.setProvince(user.getProvince());
					userManager.adminSaveWithOrgId(userTemp, orgId);
					msg.add("第" +j + "行，系统中已存在该用户，此次更新了该用户");
					} catch (Exception e) {
						msg.add("第" +j + "行，系统中已存在该用户，更新该用户时失败"+ e.getMessage());
				     }
				try{
				    adminSave(userGroup);
					successcnt = successcnt + 1;
				} catch(Exception e) {
					msg.add("第" +j + "行，系统中已存在该用户得小组注册关系，本次跳过"+ e.getMessage());
					successcnt = successcnt + 1;
				}
			} else {
				userManager.adminSaveWithOrgId(user, orgId);
				userGroup.setUserId(user.getId());
				userGroup.setUsergroupId(groupId);
				adminSave(userGroup);
				successcnt = successcnt + 1;
			}
			}catch (Exception e) {
				msg.add("第" +j + "行，插入失败 原因:"+e.getMessage());
					e.printStackTrace();
				}

}
			map.put("msg", msg);
			map.put("rowNum", effectiveNum);
			map.put("successcnt", successcnt);
			
			return map;
	}

}
